import configReader


def parseFlightResults(key, FlightResultsList):
    resultIds = FlightResultsList['resultIds']
    resultIds = [item for item in resultIds if 'sponsored' not in item and 'inline' not in item]

    results = FlightResultsList['results']
    airlineKey = key.split('/')[2]

    datas = []
    limit = int(configReader.getConfig('limit'))
    # if len(resultIds) > limit:
    #     resultIds = resultIds[:limit]

    top3AirLine = []
    for rindex, rId in enumerate(resultIds):
        result = results[rId]
        airLines = []
        if 'legs' in result:
            legs = result['legs']
            for leg in legs:
                if 'segments' in leg:
                    segments = leg['segments']
                    for segment in segments:
                        airline = segment['airline']
                        airlineName = airline['name']
                        if rindex < 3 and airlineName not in airLines:
                            airLines.append(airlineName)
        if rindex < 3:
            top3AirLine.append('(' + ','.join(airLines) + ')')

    requiredAirlines = configReader.getConfig('requiredAirlines')

    for rindex, rId in enumerate(resultIds):
        result = results[rId]
        airlines = []
        isRequired = False
        if 'legs' in result:
            legs = result['legs']
            for leg in legs:
                if 'segments' in leg:
                    segments = leg['segments']
                    for segment in segments:
                        airline = segment['airline']
                        airlineName = airline['name']
                        isRequired = isRequired or (airlineName in requiredAirlines)
                        if airlineName not in airlines:
                            airlines.append(airlineName)
        airlineName = ','.join(airlines)
        airlineName = '(' + airlineName + ')'
        airInfo = dict()

        if rindex < limit or isRequired:
            datas.append(airInfo)

        airInfo['航线'] = airlineKey
        airInfo['排名前3的航司'] = ';'.join(top3AirLine)
        airInfo['比价航司排名'] = rindex
        airInfo['比价航司'] = airlineName
        tripPrice = '-'
        if 'optionsByFare' in result:
            optionsByFare = result['optionsByFare']
            item = optionsByFare[0]
            options = item['options']
            airInfo['供应商数量'] = len(options)
            min_price_dict = getMinPrice(options)
            for i, option in enumerate(options):
                providerInfo = option['providerInfo']
                displayName = providerInfo['displayName']
                fees = option['fees']
                rawPrice = fees['rawPrice']
                if displayName == 'iWofly':
                    airInfo['自家排名'] = i + 1
                    airInfo['自家价格'] = '$' + str(rawPrice)
                    airInfo['最低价供应商'] = min_price_dict['providerName']
                    airInfo['最低价'] = '$' + str(min_price_dict['price'])
                    airInfo['自家-最低价差'] = '$' + str(int(rawPrice) - int(min_price_dict['price']))

                if displayName == 'Trip.com':
                    tripPrice = rawPrice
        if '自家排名' not in airInfo:
            airInfo['自家排名'] = '-'
            airInfo['自家价格'] = '-'
            airInfo['最低价供应商'] = min_price_dict['providerName']
            airInfo['最低价'] = '$' + str(min_price_dict['price'])
            airInfo['自家-最低价差'] = '-'

        airInfo['trip.com价格（携程）'] = '$' + str(tripPrice)

    print('----------- 查询【' + airlineKey + '】数据, ' + '查询到[' + str(len(datas)) + ']条数据' + '----------- ')
    return datas


def getMinPrice(options):
    if len(options) == 0:
        return 0
    min_price = min(options, key=lambda x: x['fees']['rawPrice'])
    return {'providerName': min_price['providerInfo']['displayName'], 'price': min_price['fees']['rawPrice']}


def getProvideInfo(provideName, options):
    for i, option in enumerate(options):
        providerInfo = option['providerInfo']
        displayName = providerInfo['displayName']
        if displayName == provideName:
            return
